from extens import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from network.NetworkModel_pb2 import UserInfo


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    account = db.Column(db.String(50), nullable=False, unique=True)
    __password = db.Column(db.String(100), nullable=False)
    name = db.Column(db.String(50), nullable=False)
    avatarUrl = db.Column(db.Text, default="")
    create_time = db.Column(db.DateTime, default=datetime.now)

    def __init__(self, account, password, name):
        self.account = account
        self.password = password
        self.name = name

    @property
    def password(self):
        return self.__password

    @password.setter
    def password(self, password):
        self.__password = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password, password)

    def get_user_info(self):
        user = UserInfo()
        user.uid = str(self.id)
        user.account = self.account
        user.name = self.name
        user.avatarUrl = self.avatarUrl
        return user
